package com.example.budget3.months;


import java.util.Calendar;

import com.example.budget3.R;
import com.example.budget3.util.UtilMethods;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.View;
import android.widget.NumberPicker.OnValueChangeListener;
import android.widget.NumberPicker;

public class MonthDialogFragment extends DialogFragment {
	private static final String MONTHS_ARG = "count";
	private static final String MONTH_STATE = "month";
	private int month = 0;
	
	@Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
		
		if(savedInstanceState!=null){
			month = savedInstanceState.getInt(MONTH_STATE);
		}
		int count = getArguments().getInt(MONTHS_ARG);
		
		Calendar now = Calendar.getInstance();
		
		View inflate = getActivity().getLayoutInflater().inflate(R.layout.select_month_dialog, null);
		
	

		// Set other dialog properties

		NumberPicker np = (NumberPicker) inflate.findViewById(R.id.monthPicker);

		np.setWrapSelectorWheel(false);
		np.setMinValue(0);
		np.setMaxValue(count - 1);
		String[] months = new String[count];
		for (int monthNum = 0; monthNum < count; monthNum++) {
			Calendar time = Calendar.getInstance();
			time.setTimeInMillis(now.getTimeInMillis());
			time.add(Calendar.MONTH, -1 * monthNum);
			months[monthNum] = UtilMethods.getMonthNameAndYear(time);
		}

		np.setDisplayedValues(months);
		np.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
		np.setOnValueChangedListener(new OnValueChangeListener() {

			@Override
			public void onValueChange(NumberPicker picker, int oldVal,
					int newVal) {
				month = newVal;
			}
		});
		np.setValue(month);
		
		// Add the buttons
		AlertDialog dialog = new AlertDialog.Builder(getActivity())
				.setView(inflate)
				.setNegativeButton("Cancel",null)
				.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						((MainActivity) getActivity()).changePage(month);
					}
				}).create();

		dialog.show();
		return dialog;

    }
	
	@Override
	public void onSaveInstanceState(Bundle arg0) {
		arg0.putInt(MONTH_STATE, month);
		super.onSaveInstanceState(arg0);
	}

}
